package com.xlg.file.center.handler;

import com.xlg.file.center.utils.Task;
import org.apache.poi.ss.usermodel.*;
import org.springframework.cglib.beans.BeanMap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author: 18310740596@163.com
 * @date: 2023-07-15 00:10:45
 * @version: v1.0
 * @describe: class responsibility
 */
public class ExcelFileHandler extends AbstractFileHandler {

    private static final String FILE_SUFFIX = ".xlsx";

    @Override
    public void writeTitle(Handler handler) throws Exception {
        // 创建excel文件
        File file = super.createFile(handler, FILE_SUFFIX);

        // 添加title
        appendContent(handler, file, handler.getTask().getTitles());

        // 设置文件
        handler.setFile(file);
    }

    private void appendContent(Handler handler, File file, List<String> titles) throws IOException {

        Workbook workbook = WorkbookFactory.create(true);
        Sheet sheet = workbook.createSheet("内容页");
        Row row = sheet.createRow(0);
        for (int i = 0; i < titles.size(); i++) {
            row.createCell(i, CellType.STRING).setCellValue(titles.get(i));
        }
        handler.getFileLine().getAndIncrement();
        try (FileOutputStream fileOutputStream = new FileOutputStream(file, true)) {
            workbook.write(fileOutputStream);
        } finally {
            workbook.close();
        }
    }

    @Override
    public void writeContent(Handler handler) throws Exception {
        Task task = handler.getTask();

        Workbook workbook = null;
        try (FileInputStream inputStream = new FileInputStream(handler.getFile())) {
            // 读取excel
            workbook = WorkbookFactory.create(inputStream);
            Sheet sheetAt = workbook.getSheetAt(0);

            // 内容写入
            task.getContents()
                    .stream()
                    .filter(Objects::nonNull)
                    .forEach(obj -> {
                        int andIncrement = handler.getFileLine().getAndIncrement();
                        Row row = sheetAt.createRow(andIncrement);
                        BeanMap beanMap = BeanMap.create(obj);
                        for (int i = 0; i < task.getTitles().size(); i++) {
                            Object o = beanMap.get(task.getTitles().get(i));
                            row.createCell(i, CellType.STRING).setCellValue(Objects.isNull(o) ? "" : String.valueOf(o));
                        }
                    });

            // excel写入文件流中
            try (FileOutputStream fos = new FileOutputStream(handler.getFile(), true)) {
                workbook.write(fos);
            }
        } finally {
            if (Objects.nonNull(workbook)) {
                workbook.close();
            }
        }
    }
}
